package com.analyse.stock.component;

import com.analyse.stock.annotation.StrategyType;
import com.analyse.stock.enums.StrategyEnum;
import com.analyse.stock.strategy.StrategyHandle;
import com.analyse.stock.strategy.IStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Slf4j
public class StockRegister implements ApplicationListener<ContextRefreshedEvent> {

    private ApplicationContext applicationContext;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        this.applicationContext = contextRefreshedEvent.getApplicationContext();

        //注册 分析/交易策略类
        this.registerStrategy();
    }

    /**
     * 将带有StrategyType注解的bean存到map中
     */
    private void registerStrategy(){
        Map<String, Object> jobHelperMap = this.applicationContext.getBeansWithAnnotation(StrategyType.class);
        if(MapUtils.isEmpty(jobHelperMap)){
            return;
        }
        jobHelperMap.forEach((beanName,bean)->{
            if(StringUtils.isBlank(beanName)){
                return;
            }
            if(bean instanceof IStrategy){
                Class<IStrategy> clz = (Class<IStrategy>) bean.getClass();
                StrategyEnum strategy = clz.getAnnotation(StrategyType.class).strategy();
                StrategyHandle.strategyMap.put(strategy.name(),clz);
            }
        });
        log.info("## 分析/交易策略注册成功 ##");
    }
}
